﻿using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Http;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using Zhp.Common.Helper;

namespace Zhp.Common.WebApp
{
    public class CurrentUser : ICurrentUser
    {
        private readonly HttpContext _httpContext;

        public CurrentUser(IHttpContextAccessor httpContextAccessor)
        {
            _httpContext = httpContextAccessor.HttpContext;
        }

        /// <summary>
        /// 当前登录用户UserID
        /// </summary>
        public long UserId => _httpContext.User.FindFirst(ClaimTypes.Sid) == null ? 0L : Convert.ToInt64(_httpContext.User.FindFirst(ClaimTypes.Sid).Value);

        /// <summary>
        /// jwt编号
        /// </summary>
        public long TokenId => _httpContext.User.FindFirst(JwtRegisteredClaimNames.Jti) == null ? 0L : Convert.ToInt64(_httpContext.User.FindFirst(JwtRegisteredClaimNames.Jti).Value);

        /// <summary>
        /// 当前登录用户名称
        /// </summary>
        public string Name => _httpContext.User.Identity?.Name;

        /// <summary>
        /// 当前登录用户昵称
        /// </summary>
        public string NickName => _httpContext.User.FindFirst(ClaimTypes.GivenName) == null ? string.Empty : _httpContext.User.FindFirst(ClaimTypes.GivenName).Value;

        /// <summary>
        /// 当前登录用户所有角色ID
        /// </summary>
        public List<long> RoleIds => _httpContext.User.FindFirst(ClaimTypes.Role) == null ? new List<long>() : _httpContext.User.FindFirst(ClaimTypes.Role).Value.ToObject<List<long>>();

        /// <summary>
        /// 远程请求IP
        /// </summary>
        public string RemoteIpAddress => _httpContext.Connection.RemoteIpAddress.ToString();


        /// <summary>
        /// 请求携带的Token
        /// </summary>
        /// <returns></returns>
        public string GetToken()
        {
            return _httpContext.Request.Headers["Authorization"].ToString().Replace(JwtBearerDefaults.AuthenticationScheme + " ", "");
        }

        /// <summary>
        /// 是否已认证
        /// </summary>
        /// <returns></returns>
        public bool IsAuthenticated()
        {
            return _httpContext.User.Identity is { IsAuthenticated: true };
        }

        /// <summary>
        /// 获取用户身份权限
        /// </summary>
        /// <returns></returns>
        public IEnumerable<Claim> GetClaimsIdentity()
        {
            return _httpContext.User.Claims;
        }

        /// <summary>
        /// 根据权限类型获取详细权限
        /// </summary>
        /// <param name="claimType"></param>
        /// <returns></returns>
        public List<string> GetClaimValueByType(string claimType)
        {
            return (from item in GetClaimsIdentity()
                    where item.Type == claimType
                    select item.Value).ToList();
        }

        public List<string> GetUserInfoFromToken(string claimType)
        {
            var jwtHandler = new JwtSecurityTokenHandler();
            if (!string.IsNullOrEmpty(GetToken()))
            {
                JwtSecurityToken jwtToken = jwtHandler.ReadJwtToken(GetToken());

                return (from item in jwtToken.Claims
                        where item.Type == claimType
                        select item.Value).ToList();
            }

            return new List<string>();
        }
    }
}
